package com.sky.service.impl;


import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WorkspaceService workspaceService;


    /**
     * 根据开始时间结束时间进行营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
//        从begin开始一天一天的增加 知道等于end
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
//        转换为String并用","分割
        String dateString = StringUtils.join(dateList, ",");

//        查询当日营业额
        ArrayList<BigDecimal> dateAmountList = new ArrayList();
        Integer status = Orders.COMPLETED;
        for (LocalDate localDate : dateList) {
//            获取当日最低时间
            LocalDateTime localDateBegin = LocalDateTime.of(localDate, LocalTime.MIN);
//            获取当日最高时间
            LocalDateTime localDateEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            BigDecimal dateAmount = reportMapper.selectByDateNow(localDateBegin, localDateEnd, status);
            dateAmountList.add(dateAmount);
        }
        String dateAmountString = StringUtils.join(dateAmountList, ",");
        return new TurnoverReportVO(dateString, dateAmountString);
    }

    /**
     * 统计用户数据
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
//        从begin开始一天一天的增加 直到等于end
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
//        转换为String并用","分割
        String dateString = StringUtils.join(dateList, ",");

//        查询当天用户
        ArrayList<Integer> userNowList = new ArrayList();
        Integer status = Orders.COMPLETED;
        for (LocalDate localDate : dateList) {
//            获取当日最低时间
            LocalDateTime localDateBegin = LocalDateTime.of(localDate, LocalTime.MIN);
//            获取当日最高时间
            LocalDateTime localDateEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            Integer userCountByDate = reportMapper.selectUserCountByDate(localDateBegin, localDateEnd, status);
            userNowList.add(userCountByDate);
        }
        String userNowListString = StringUtils.join(userNowList, ",");

//        查询总用户量
        Integer userCountByDate = reportMapper.selectTotalUser(status);
        String userCountByDateString = String.valueOf(userCountByDate);
        return new UserReportVO(dateString, userCountByDateString, userNowListString);
    }

    /**
     * 对订单进行统计
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {

        Integer status = Orders.COMPLETED;

//        获取时间列表
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
//        从begin开始一天一天的增加 直到等于end
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
//        转换为String并用","分割
        String dateString = StringUtils.join(dateList, ",");


//        订单数列表
        ArrayList<Integer> OrderList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
//            获取当日最低时间
            LocalDateTime localDateBegin = LocalDateTime.of(localDate, LocalTime.MIN);
//            获取当日最高时间
            LocalDateTime localDateEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            Integer orderCount = reportMapper.selectOrderCount(localDateBegin, localDateEnd);
            OrderList.add(orderCount);
        }
        String OrderListString = StringUtils.join(OrderList, ",");

//        订单总数
        Integer orderAmount = reportMapper.selectAllOrdersAmount();

//        有效订单数
        Integer trueOrderAmount = reportMapper.selectTrueOrderAmount(status);

//        订单完成率
        double orderCompletionRate = new BigDecimal((float) trueOrderAmount / orderAmount).setScale(2, RoundingMode.HALF_UP).doubleValue();

//        有效订单列表
        ArrayList<Object> orderCompletionList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
//            获取当日最低时间
            LocalDateTime localDateBegin = LocalDateTime.of(localDate, LocalTime.MIN);
//            获取当日最高时间
            LocalDateTime localDateEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            Integer orderComplateNowDate = reportMapper.selectComplateOrder(localDateBegin, localDateEnd, status);
            orderCompletionList.add(orderComplateNowDate);
        }
        String orderCompletionListString = StringUtils.join(orderCompletionList, ",");

        return new OrderReportVO(dateString, OrderListString, orderCompletionListString, orderAmount, trueOrderAmount, orderCompletionRate);
    }

    /**
     * 查询销售排行榜前10
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        Integer status = Orders.COMPLETED;
//        获取时间列表
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
//        从begin开始一天一天的增加 直到等于end
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        ArrayList<String> top10 = new ArrayList<>();
        ArrayList<Integer> top10Numbers = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            log.info("当前时间为:{}", localDate);
//            获取当日最低时间
            LocalDateTime localDateBegin = LocalDateTime.of(localDate, LocalTime.MIN);
//            获取当日最高时间
            LocalDateTime localDateEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            List<Integer> orderId = reportMapper.selectOrderCommodityId(localDateBegin, localDateEnd, status);
            for (Integer i : orderId) {
                log.info("当前订单id为:{}", i);
                List<String> top10Name = reportMapper.selectTopCommodifyName(i);
                for (String s : top10Name) {
                    log.info("当前商品为:{}",s);
                    if (top10.contains(s)) {
                        List<Integer> numbers = reportMapper.selectTopNumberByNameStep(s, i, 1);
                        log.info("查看了:(1){}条数据", numbers);
                        int index = top10.indexOf(s);
                        top10Numbers.addAll(index, numbers);
                        top10Numbers.remove(index + 1);
//                        top10Numbers.addAll(numbers);
                    }else {
                        List<Integer> numbers = reportMapper.selectTopNumberByName(s, i);
                        log.info("查看了:(2){}条数据", numbers);
                        top10Numbers.addAll(numbers);
                        top10.add(s);
                    }
                }

//                根据排行前10的商品名称查询销量
//                for (String s : top10Name) {
////                判断当前集合元素是否重复
//                    List<Integer> numbers = reportMapper.selectTopNumberByName(s, i);
//                    top10Numbers.addAll(numbers);
//
//                }
            }
        }
        String top10String = StringUtils.join(top10, ",");
        String top10NumbersString = StringUtils.join(top10Numbers, ",");
        return new SalesTop10ReportVO(top10String, top10NumbersString);
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    public void export(HttpServletResponse response) {
//        获取营业数据 查询最近30天的
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);
        BusinessDataVO businessDataVO = workspaceService.businessData(begin, end);

//        通过POI写入到excel
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/model.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);

            XSSFSheet sheet1 = excel.getSheet("Sheet1");
//            填充数据--时间
            sheet1.getRow(1).getCell(1).setCellValue("时间: "+dateBegin+ "至"+ dateEnd);
//            填充数据--概览数据
            sheet1.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            sheet1.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            sheet1.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            sheet1.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            sheet1.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
//            填充数据--明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                LocalDateTime beginLot = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime endLot = LocalDateTime.of(date, LocalTime.MAX);
                BusinessDataVO businessData = workspaceService.businessData(beginLot, endLot);
                sheet1.getRow(i + 7).getCell(1).setCellValue(String.valueOf(date));
                sheet1.getRow(i + 7).getCell(2).setCellValue(businessData.getTurnover());
                sheet1.getRow(i + 7).getCell(3).setCellValue(businessData.getValidOrderCount());
                sheet1.getRow(i + 7).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet1.getRow(i + 7).getCell(5).setCellValue(businessData.getUnitPrice());
                sheet1.getRow(i + 7).getCell(5).setCellValue(businessData.getNewUsers());
            }

//        通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
